package com.tanhua.server.service;


import com.tanhua.domain.SoulTest.SoulTestResult;
import com.tanhua.domain.SoulTest.UserSoulResult;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.dubbo.api.SoulTest.SoulTestApi;
import com.tanhua.dubbo.api.db.UserInfoApi;
import com.tanhua.server.interceptors.UserHolder;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

/**
 * @author 钱柏羽
 * 测灵魂服务类
 */
@Service
public class TestSoulService {

    @Reference
    private SoulTestApi soulTestApi;
    @Reference
    private UserInfoApi userInfoApi;
    @Autowired
    private StringRedisTemplate redisTemplate;
    public ResponseEntity surveyView() {
        Long userId = UserHolder.getUserId();
        return ResponseEntity.ok(soulTestApi.getSoulTests(userId));
    }

    public String getSurveyScore(String answer) {
        Long userId = UserHolder.getUserId();
        String facility = soulTestApi.getFacilityStatus(userId);
        soulTestApi.changeFacilityStatus(UserHolder.getUserId());
        Integer surveyScore = soulTestApi.getSurveyScore(answer.
                replaceAll("\"questionId\"|[:]|\"optionId\"", "").
                replaceAll("([\\{]|[\\[])", "(").
                replaceAll("([\\}]|[\\]])", ")"));
        soulTestApi.saveUserScore(userId,surveyScore,facility);
        return surveyScore.toString()+facility;
    }

    public SoulTestResult reportView(String reportScore) {
        return soulTestSettings(reportScore);
    }

    public SoulTestResult soulTestSettings(String reportScore) {
        Long userId = UserHolder.getUserId();
        String scoreType = soulTestApi.findScoreType(reportScore);
        SoulTestResult soulTestResult = soulTestApi.getSoulTestConclusion(reportScore);
        saveReportResult(scoreType);
        return SoulTestResult.setAttachment(soulTestResult,soulTestApi.findDimensions(scoreType),soulTestApi.findSimilarUser(scoreType,userId));
    }

    public void saveReportResult(String scoreType) {
        Long userId = UserHolder.getUserId();
        if (soulTestApi.getUserSoulResult(userId) == null) {
            UserInfo userInfo = userInfoApi.findById(userId);
            soulTestApi.saveReportResult(new UserSoulResult(userInfo.getCoverPic(), scoreType, userId));
        } else {
            soulTestApi.updateUserSoulResult(userId, scoreType);
        }
    }
}
